<template>
	<view>
		<uni-popup ref="selcon" zindex type="bottom" @maskClick="maskClick" :safeArea="false">
			<view class="comBotBx p_rlt" @touchmove.stop.prevent="" :class="{ipx:props.isPhonex}">
				<view class="bx_top">
					<view class="bx_top_titles">
						无法配送到当前收货位置
						<view class="close_ico point" @click="close">
							收起<text class="cuIcon-unfold"></text>
						</view>
					</view>
					<view class="bx_top_store">
						<text
							class="fcon-a-dingwei4 margin-right-xs"></text>{{(shopStore.shopInfo.vnick&&shopStore.shopInfo.vnick||'')}}
					</view>
					<view class="bx_top_btns point"
						@click.stop="mnavTo('/pages/others/addressList/addressList?source=menu' + '&adressInfo=' + userStore.curSelecAdress.naddress_id,true)">
						更换收货地址
					</view>
				</view>
				<view class="bx_conts">
					<empty positions="absolute" :empty="storeList.length<=0" :zIndexs="100"
						:imgUrl="env.FileUrl+'food/empty/images/empty_ico01.png'" content="抱歉！您附近没有可配送门店"></empty>
					<view class="titles">请选择离您最近的门店</view>
					<view class="storeList" v-for="(item,index) in storeList" :key="index" @click.stop="changeStore(item)">
						<view class="store_lefr">
							<view class="flex align-center">
								<!-- <view class="left_name">{{item&&item.vnick.length > 6 ? item.vnick.substring(3) : item.vnick}}</view> -->
								<view class="left_name">{{item.vnick}}
									<!-- <text class="text-sm text-c9 text-nomal" v-if="!(item.work_status=='233' || item.work_status=='974')">暂未开通</text> -->
								</view>
								<!-- <view class="tags">{{item.storeType}}</view> -->
							</view>
							<view class="left_dis">
								{{userStore.getAdresGps&&userStore.getAdresGps.hasGps?'距离':'距您'}}{{ item.distance ? item.distance : '0' }}{{ item.distanceUnit ? item.distanceUnit : 'm' }}
							</view>
						</view>
						<view class="right_icon">
							<text class="cuIcon-roundright" style="color: #333;font-size: 52rpx;"></text>
						</view>
					</view>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script setup lang="ts">
	import { ref, defineEmits, reactive } from 'vue';
	import mapi from '@/utils/mapi';
	import { mnavTo } from '@/utils/helper';
	import { env } from '@/api/env.js'
	import { useShopStore } from '@/stores/shopStore';
	import { useUserStore } from '@/stores/commonStore';
	import { getStoreList, queryDistance } from '@/api/vmeitime-http/index.js'
	const shopStore = useShopStore();
	const userStore = useUserStore()
	const props = defineProps({
		isPhonex: {
			type: Boolean,
			default: false
		},
		addData: {
			type: Array,
			default: []
		}
	});
	const emit = defineEmits(["maskClick", "changeSt"])
	const selcon = ref()
	const storeList = ref([])
	const longitude = ref()
	const latitude = ref()
	let state = reactive({
		latitude: 28.208399,
		longitude: 113.06463,
		mapLatitude: 28.208399,
		mapLongitude: 113.06463,
		covers: [],
		scale: 14, //地图层级，取值范围为5-18，默认16，14最优，11看长沙市
	})
	const porpsMember=ref('')
	const open = (v : any) => {
		// if (!v) {
		// 	// uni.getLocation({
		// 	// 	//获取当前的位置坐标
		// 	// 	type: 'gcj02', //默认为 wgs84 返回 gps 坐标，gcj02 返回国测局坐标，可用于 uni.openLocation 的坐标
		// 	// 	success: function (res) {
		// 	// 		console.log('当前位置的经度：' + res.longitude);
		// 	// 		console.log('当前位置的纬度：' + res.latitude);
		// 	// 		longitude.value = res.longitude;
		// 	// 		latitude.value = res.latitude;
		// 	// 		getCarLists(res.longitude, res.latitude)
		// 	// 	},
		// 	// 	fail: function (err) {
		// 	// 		console.log('定位失败', err);
		// 	// 	}
		// 	// });
			
		// } else {
		// 	// selcon.value.open()
			
		// }
     getCarLists('init')
	}

	const getCarLists = async (source:any='') => {
		let skuArray = props.addData && props.addData.shopParams ? props.addData.shopParams.map((item : any) => item.sku).join(',') : ''
		const paramData = {
			longitude: userStore.curSelecAdress.latitude ? userStore.curSelecAdress.longitude : 113.06463,
			latitude: userStore.curSelecAdress.latitude ? userStore.curSelecAdress.latitude : 28.208399,
			vtype_two_category: 0,
			vtype: '835',
			nmember_id: '',
			sku: skuArray || '',
			vIsFirstShop: '猪会飞',
			curPage: 1,
			pageSize: 200,
			scene: 'limit_distance',//传了只返回指定配送距离的(指定配送距离是后台配置的)
		};
		console.log(paramData, "paramData")
		return await fetchStoreList(paramData, getStoreList,source);
	
		// selcon.value.open()
	};
	const fetchStoreList = async (paramData : any, apiFunction : any,source:any='') => {
		return new Promise(async (resolve, reject) => {
			try {
				let res = await apiFunction(paramData);
				if (!res.result) throw new Error('获取门店失败!');
				let resulFinal = processStoreData(res.object, state.latitude);
				storeList.value = []
				for (let item of resulFinal) {
					// let resultName = item.vnick.length > 6 ? item.vnick.substring(3) : item.vnick
					storeList.value.push(item)
					// {
					// 	storeName: resultName,
					// 	distance: item.distance + item.distanceUnit,
					// 	storeType: "全品店",
					// 	sellMemberId: item.nmember_id
					// }
				}
				if(storeList.value.length==1&&storeList.value[0].nmember_id==shopStore.curSellerMemberId&&source==''){
					resolve(true)
				}else{
					selcon.value.open()
					resolve(false)
				}
			} catch (e) {
				mapi.msg('获取门店失败!');
			}
		})
	}
	const processStoreData = (data : any, latitude : any) => {
		let array = [];
		for (let key in data) {
			let dist = latitude ? key.split('.')[0] : '';
			data[key]['distanceUnit'] = dist.length > 3 ? 'km' : 'm';
			dist = dist.length > 3 ? (Number(dist) / 1000).toFixed(2) : dist;
			data[key]['distance'] = dist;
			array.push(data[key]);
		}
		return array;
	};
	
	const close = () => {
		selcon.value?.close()
	}

	const maskClick = (e : any) => {
		// console.log('car-maskClick',e);
		emit("maskClick")
	}
	const getDistance = (params : any = {}, source : any = '') => {
		if (source == 'menu') {
			getCarLists()
		}
		return new Promise(async (resolve, reject) => {
			try {
				let reParams = {
					longitude: params.lo, //选择门店经度
					latitude: params.la, //选择门店纬度
					nowLongitude: userStore.curSelecAdress.latitude ? userStore.curSelecAdress.longitude : shopStore.nowLocaGps.lo,
					nowLatitude: userStore.curSelecAdress.latitude ? userStore.curSelecAdress.latitude : shopStore.nowLocaGps.la
				}
				let result = await queryDistance(reParams)
				let nresult : any = {
					allowSent: false
				}
				//如果距离小于等于后台返回配置的距离，直接加入购物车，
				//否则调接口查询符合配送距离和有再来一单内商品的门店，如果只返回了一个门店且返回的门店和当前门店一致，则不弹弹窗直接加入购物车，否则弹出选择门店的弹窗，选择门店后加入购物车
				if (result.result) {
					nresult.allowSent = result.object.range <= shopStore.sendDistance ? true : false	
					if(!nresult.allowSent){
						let res=await getCarLists()
						if(res){
							nresult.allowSent=true
						}else{
							nresult.allowSent=false
						}
					}
					
				} else {
					nresult.allowSent = false
				}
				resolve(nresult)
			} catch (err) {
				reject(err);
			}
		})
	}
	const changeStore = (item : any) => {
		// if (!(item.work_status == '233' || item.work_status == '974')) {
		// 	return
		// }
		shopStore.setOrderAgain(false)
		userStore.setChangeAdress(false);
		shopStore.setQrShop('');
		shopStore.setShop(item)
		emit('changeSt')
	}
	defineExpose({ open, close, getDistance })
</script>

<style lang="scss" scoped>
	.comBotBx {
		height: 70vh;
		background: #F5F5F5;

		&.ipx {
			padding-bottom: 170rpx;
		}

		.bx_top {
			width: 100%;
			height: 320rpx;
			border-radius: 12rpx 12rpx 0px 0px;
			background: #FFF;
			padding-top: 40rpx;

			.bx_top_titles {
				text-align: center;
				line-height: 45rpx;
				position: relative;
				color: #333;
				font-size: 32rpx;
				font-weight: 700;
				height: 45rpx;

				.close_ico {
					color: #999;
					font-size: 28rpx;
					font-weight: 400;
					position: absolute;
					top: 0;
					right: 20rpx;
				}
			}

			.bx_top_store {
				text-align: center;
				line-height: 45rpx;
				position: relative;
				height: 45rpx;
				margin-top: 50rpx;
				color: #999;
				font-size: 28rpx;
				font-weight: 400;
			}

			.bx_top_btns {
				width: 236rpx;
				height: 52rpx;
				line-height: 52rpx;
				margin: 50rpx auto;
				border-radius: 26rpx;
				background: #53A87F;
				color: #FFF;
				font-size: 28rpx;
				font-weight: 400;
				text-align: center;
			}
		}

		.bx_conts {
			height: calc(100% - 290rpx);
			position: relative;
			padding-top: 30rpx;

			.titles {
				width: 100%;
				height: 45rpx;
				text-align: center;
				color: #333;
				font-size: 28rpx;
				font-weight: 400;
			}

			.storeList {
				width: 654rpx;
				height: auto;
				border-radius: 16rpx;
				background: #FFF;
				margin: auto;
				margin-top: 30rpx;
				display: flex;
				justify-content: space-between;

				.store_lefr {
					width: 80%;
					height: auto;
					padding: 40rpx 20rpx 30rpx 40rpx;

					.left_name {
						color: #333;
						text-align: left;
						font-family: "Microsoft YaHei UI";
						font-size: 32rpx;
						font-style: normal;
						font-weight: 700;
					}

					.left_dis {
						color: #666;
						text-align: left;
						font-family: "Microsoft YaHei UI";
						font-size: 28rpx;
						font-style: normal;
						font-weight: 400;
						margin-top: 30rpx;
					}
				}

				.right_icon {
					width: 20%;
					height: auto;
					display: flex;
					justify-content: center;
					align-items: center;
				}

				.tags {
					min-width: 90rpx;
					height: 40rpx;
					line-height: 40rpx;
					color: #fff;
					margin-left: 10rpx;
					border-radius: 98rpx;
					font-size: 28rpx;
					padding: 0rpx 14rpx 0rpx 14rpx;
					// margin-top: 6rpx;
					background-color: #53A87F;
					text-align: center;
				}
			}
		}
	}
</style>